import Flutter
import UIKit

public class SwiftVideoEditorPlugin: NSObject, FlutterPlugin, FlutterStreamHandler {
    
    static var plugin: SwiftVideoEditorPlugin?
    var channel: FlutterMethodChannel?
     var eventChannel: FlutterEventChannel?
     var eventSink: FlutterEventSink?
    var registrar: FlutterPluginRegistrar?
     
    
    public func onCancel(withArguments arguments: Any?) -> FlutterError? {
        return nil
    }
    
    public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        self.eventSink = events;
        return nil
    }
    static public  func register(with registrar: FlutterPluginRegistrar) {
        SwiftVideoEditorPlugin.plugin = SwiftVideoEditorPlugin();
        SwiftVideoEditorPlugin.plugin!.registrar = registrar;
        SwiftVideoEditorPlugin.plugin!.channel = FlutterMethodChannel(name: "video_editor", binaryMessenger: registrar.messenger())
        registrar.addMethodCallDelegate(SwiftVideoEditorPlugin.plugin!, channel: SwiftVideoEditorPlugin.plugin!.channel! )
        SwiftVideoEditorPlugin.plugin!.eventChannel = FlutterEventChannel(name: "video_editor_progress", binaryMessenger: registrar.messenger())
        SwiftVideoEditorPlugin.plugin!.eventChannel?.setStreamHandler( SwiftVideoEditorPlugin.plugin!);
    
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case "writeVideofile":
        let video = VideoGeneratorService()
        guard let args = call.arguments as? [String: Any] else {
          result(FlutterError(code: "arguments_not_found",
                            message: "the arguments is not found.",
                            details: nil))
          return
        }
        guard let srcName = args["srcFilePath"] as? String else {
                result(FlutterError(code: "src_file_path_not_found",
                                  message: "the src file path sr is not found.",
                                  details: nil))
                return
        }
        guard let destName = args["destFilePath"] as? String else {
                result(FlutterError(code: "dest_file_path_not_found",
                                  message: "the dest file path is not found.",
                                  details: nil))
                return
        }
        guard let processing = args["processing"] as?  [String: [[String: Any]]] else {
                result(FlutterError(code: "processing_data_not_found",
                                  message: "the processing is not found.",
                                  details: nil))
                return
        }
        video.writeVideofile(srcPath: srcName, destPath: destName, processing: processing,eventSink:  SwiftVideoEditorPlugin.plugin!.eventSink!, result: result)
    default:
        result("iOS d" + UIDevice.current.systemVersion)
    }
  }
}
